package cn.lanqiao.springboot.service;

import cn.lanqiao.springboot.entity.Role;
import cn.lanqiao.springboot.mapper.RoleMapper;
import cn.lanqiao.springboot.mapper.RoleMenuMapper;
import cn.lanqiao.springboot.vo.InsertOrUpdateRoleVO;
import cn.lanqiao.springboot.vo.QueryRoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    RoleMenuMapper roleMenuMapper;

    public List<Role> getList(QueryRoleVO queryRoleVO) {
        return roleMapper.getList(queryRoleVO);
    }

    @Transactional
    public void insert(InsertOrUpdateRoleVO insertOrUpdateRoleVO){
        //插入role
        roleMapper.insert(insertOrUpdateRoleVO);
        //插入role_menu
        for (int menuId : insertOrUpdateRoleVO.menuIds){
            roleMenuMapper.insert(insertOrUpdateRoleVO.getRoleId(),menuId);
        }
    }

    @Transactional
    @CacheEvict(value = "roleId",key = "#insertOrUpdateRoleVO.roleId")
    public void update(InsertOrUpdateRoleVO insertOrUpdateRoleVO){
        //更新role
        roleMapper.update(insertOrUpdateRoleVO);
        //删除role_menu
        roleMenuMapper.delete(insertOrUpdateRoleVO.getRoleId());
        //插入role_menu
        for (int menuId : insertOrUpdateRoleVO.menuIds){
            roleMenuMapper.insert(insertOrUpdateRoleVO.getRoleId(),menuId);
        }
    }
}
